package com.water_work_form.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.deepoove.poi.XWPFTemplate;
import com.water_work_form.entity.BasicPhLiquid;
import com.water_work_form.entity.RecordPotentialPh;
import com.water_work_form.mapper.*;
import com.water_work_form.service.RecordPotentialPhService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 * 记录——电位法检测pH原始记录 服务实现类
 * </p>
 *
 * @author xuke
 * @since 2023-09-14
 */
@Service
public class RecordPotentialPhServiceImpl extends ServiceImpl<RecordPotentialPhMapper, RecordPotentialPh> implements RecordPotentialPhService {

    @Autowired
    RecordPotentialPhMapper recordPotentialPhMapper;

    @Autowired
    BasicFormMapper basicFormMapper;

    @Autowired
    BasicDeviceMapper basicDeviceMapper;

    @Autowired
    BasicRestrictionMapper basicRestrictionMapper;

    @Autowired
    BasicWaterMapper basicWaterMapper;

    @Autowired
    BasicPhLiquidMapper basicPhLiquidMapper;

    @Autowired
    BasicPhDiluteMapper basicPhDiluteMapper;

    @Value("${file.templateFilePath}")
    private String templateFilePath;

    @Value("${file.destFilePath}")
    private String destFilePath;

    /**
     * 记录——电位法检测pH原始记录 项目查询（两个查询项+分页）
     * @param checkStartDate 检测日期（check_date）范围查询的开始日期 若为空则不进行此项查询，否则返回check_date大于checkStartDate的数据
     * @param checkEndDate 检测日期（check_date）范围查询的结束日期 若为空则不进行此项查询，否则返回check_date小于checkEndDate的数据
     * @param checkSite 检测地点（check_site） 若为空则不进行此项查询，否则进行模糊查询
     * @param current 分页查询 当前页数
     * @param size 分页查询 每页最大数据量
     * @return 返回上述查询后的数据 按照状态（status）、领样日期（receive_date）、检测日期（check_date）的顺序进行升序排序
     */
    @Override
    public IPage<RecordPotentialPh> selectRecordPotentialPh(String checkStartDate, String checkEndDate, String checkSite, String status, Integer current, Integer size){
        QueryWrapper<RecordPotentialPh> queryWrapper = new QueryWrapper<>();
        if(!checkStartDate.isEmpty()){
            queryWrapper.ge("check_date", checkStartDate);
        }
        if(!checkEndDate.isEmpty()){
            queryWrapper.le("check_date", checkEndDate);
        }
        if(!checkSite.isEmpty()){
            queryWrapper.like("check_site", checkSite);
        }
        if(!status.isEmpty()){
            queryWrapper.eq("status", status);
        }
        queryWrapper.orderByAsc("status", "receive_date", "check_date");
        IPage<RecordPotentialPh> page = new Page<>(current, size);
        return this.page(page, queryWrapper);
    }

    /**
     * 记录——电位法检测pH原始记录 基础表数据查询
     * @param name form表name查询项
     * @param type device表type查询项
     * @param restrictionName restriction表name查询项
     * @param waterId water表id查询项
     * @param batchNumber1 ph_liquid表batch_number查询项
     * @param batchNumber2 ph_liquid表batch_number查询项
     * @param batchNumber3 ph_liquid表batch_number查询项
     * @param diluteNo ph_dilute表dilute_no查询项
     * @return 返回符合上述条件的数据 唯一查询项以表名为键名，多个查询项则以查询项数字编号
     */
    @Override
    public Map<String,Object> selectBasicPotentialPh(String name, String type, String restrictionName, String waterId, String batchNumber1, String batchNumber2, String batchNumber3, String diluteNo ) {
        Map<String,Object> map = new HashMap<>();
        map.put("form", basicFormMapper.getOneByName(name));
        map.put("device", basicDeviceMapper.getOneByName(type));
        map.put("restriction", basicRestrictionMapper.getOneByName(restrictionName));
        map.put("water", basicWaterMapper.getOneByName(waterId));
        QueryWrapper<BasicPhLiquid> queryWrapper = new QueryWrapper<>();
        map.put("phLiquid", basicPhLiquidMapper.selectList(queryWrapper
                .eq("batch_number", batchNumber1).or().eq("batch_number", batchNumber2).or().eq("batch_number", batchNumber3)
                .select("batch_number", "effective_date", "correction_point")));
        map.put("phDilute", basicPhDiluteMapper.getOneByName(diluteNo));
        return map;
    }

    /**
     * 记录——电位法检测pH原始记录 数据表导出
     * @param recordPotentialPh 需要导出的数据表
     * @throws IOException 异常
     */
    @Override
    public void downloadRecordPotentialPh(RecordPotentialPh recordPotentialPh) throws IOException {
        Map<String, Object> data = new HashMap<String, Object>();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");  //日期格式化
        JSONObject checkValue =  JSON.parseObject(recordPotentialPh.getCheckValue());
        JSONObject rawWater =  JSON.parseObject(recordPotentialPh.getRawWater());
        JSONObject tapWater =  JSON.parseObject(recordPotentialPh.getTapWater());
        data.put("receiveDate",dateFormat.format(recordPotentialPh.getReceiveDate()));
        data.put("checkDate", dateFormat.format(recordPotentialPh.getCheckDate()));
        data.put("checkValue", checkValue);
        data.put("rawWater", rawWater);
        data.put("tapWater", tapWater);
        data.put("list", recordPotentialPh);
        XWPFTemplate compile = XWPFTemplate.compile(templateFilePath + "RecordPotentialPh.docx");
        compile.render(data);
        compile.writeToFile(destFilePath + recordPotentialPh.getId() + "out_recordPotentialPh.docx");
        compile.close();
    }

}
